<?php
namespace Protocols;
require_once __DIR__.'/../common/Bencode.class.php';
require_once __DIR__.'/../common/Log.php';

use Workerman\Connection\UdpConnection;
use common\Log;

class DHT  
{

    public static function encode($buffer,$connection){


        if(!isset($buffer['t']) && isset($connection->response_data['t'])){
            $buffer['t'] = $connection->response_data['t'];
        }

        if(!isset($buffer['y'])){
            $buffer['y'] = 'q';
        }

        return \Bencode::encode($buffer);
    }

    public static function decode($buffer,$connection){


        $data = \Bencode::decode($buffer);

        if(!isset($data['t'])){
            Log::record('missing key t','error');
            $connection->onError($connection,401,'missing key "t"');

            return '';
        }

        if(!isset($data['y'])){
            Log::record('missing key y','error');
            $connection->onError($connection,401,'missing key "y"');

            return '';
        }

        if(isset($data['r'])){
            $connection->nid = $data['r']['id'];
        }

        if(isset($data['a'])){
            $connection->nid = $data['a']['id'];
        }

        $connection->response_data['t'] = $data['t'];   

        return $data;

    }

}
